package com.weng.sso.server.helper;


import com.weng.sso.core.config.SsoConfig;
import com.weng.sso.core.model.SsoUser;
import com.weng.sso.server.store.SsoStore;
import com.weng.sso.server.utils.CookieUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SsoWebLoginHelper {

    /**
     * client login
     *
     * @param response
     * @param sessionId
     * @param ifRemember    true: cookie not expire, false: expire when browser close （server cookie）
     * @param ssoUser
     */
    public static void login(HttpServletResponse response,
                             String sessionId,
                             SsoUser ssoUser,
                             boolean ifRemember) {

        SsoStore.put(sessionId, ssoUser);
        CookieUtil.set(response, SsoConfig.SSO_SESSIONID, sessionId, ifRemember);
    }

    /**
     *
     * @param request
     * @param response
     */
    public static void logout(HttpServletRequest request,
                              HttpServletResponse response) {

        String cookieSessionId = CookieUtil.getValue(request, SsoConfig.SSO_SESSIONID);
        if (cookieSessionId==null) {
            return;
        }

        SsoStore.remove(cookieSessionId);

        CookieUtil.remove(request, response, SsoConfig.SSO_SESSIONID);
    }



    /**
     * login check
     *
     * @param request
     * @param response
     * @return
     */
    public static SsoUser loginCheck(HttpServletRequest request, HttpServletResponse response){

        String cookieSessionId = CookieUtil.getValue(request, SsoConfig.SSO_SESSIONID);

        SsoUser ssoUser = SsoTokenLoginHelper.loginCheck(cookieSessionId);
        if (ssoUser != null) {
            return ssoUser;
        }

        SsoWebLoginHelper.removeSessionIdByCookie(request, response);

        String paramSessionId = request.getParameter(SsoConfig.SSO_SESSIONID);
        if (ssoUser != null && paramSessionId!=null) {
            ssoUser.setFreshTime(System.currentTimeMillis());
            SsoStore.put(paramSessionId, ssoUser);
            CookieUtil.set(response, SsoConfig.SSO_SESSIONID, paramSessionId, false);    // expire when browser close （client cookie）
            return ssoUser;
        }

        return null;
    }


    /**
     * client logout, cookie only
     *
     * @param request
     * @param response
     */
    public static void removeSessionIdByCookie(HttpServletRequest request, HttpServletResponse response) {
        CookieUtil.remove(request, response, SsoConfig.SSO_SESSIONID);
    }

    /**
     * get sessionid by cookie
     *
     * @param request
     * @return
     */
    public static String getSessionIdByCookie(HttpServletRequest request) {
        String cookieSessionId = CookieUtil.getValue(request, SsoConfig.SSO_SESSIONID);
        return cookieSessionId;
    }


}
